package priv.dk.springboot.handler;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import priv.dk.springboot.exception.BusinessException;
import priv.dk.springboot.util.CommonUtil;
import priv.dk.springboot.util.RespBean;

import java.sql.SQLException;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理自定义业务异常
     *
     * @param exception 自定义业务异常
     * @return respBean
     */
    @ExceptionHandler(BusinessException.class)
    public RespBean<String> handlerBusinessException(BusinessException exception) {
        return RespBean.error(exception.getCode(), exception.getMessage());
    }

    /**
     * 处理SQL异常
     * @param exception sql异常
     * @return respBean
     */
    @ExceptionHandler(SQLException.class)
    public RespBean<String> handlerSQLException(SQLException exception) {
        if (exception.getMessage().contains("Duplicate entry")) {
            return RespBean.error(CommonUtil.SQL_ERROR, "重复的条目");
        }
        return RespBean.error(CommonUtil.SQL_ERROR, exception.getMessage());
    }
}
